home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / CPTUTT22.ZIP / CHAP05.TXT < prev    next >
Text File  |  1992-01-20  |  45KB  |  944 lines

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.                                                         Chapter 5
  8.                                                     ENCAPSULATION
  9.  
  10. As mentioned in Chapter 1, object oriented programming will seem
  11. very unnatural to a programmer with a lot of procedural programming
  12. experience.  This chapter is the beginning of the definition of
  13. object oriented programming, and we will study the topic of
  14. encapsulation which is a "divide and conquer" technique.  As we
  15. stated earlier, there are a lot of new terms used with object
  16. oriented programming.  Don't be intimidated by the new terminology,
  17. we will study the terms one at a time in a meaningful order.
  18.  
  19. Encapsulation is the process of forming objects which we will
  20. discuss throughout this chapter.  An encapsulated object is often
  21. called an abstract data type and it is what object oriented
  22. programming is all about.  Without encapsulation, which involves
  23. the use of one or more classes, there is no object oriented
  24. programming.  Of course there are other topics concerning object
  25. oriented programming, but this is the cornerstone.
  26.  
  27.  
  28. WHY BOTHER WITH ENCAPSULATION?
  29. _________________________________________________________________
  30.  
  31. We need encapsulation because we are human, and humans make errors.
  32. When we properly encapsulate some code, we actually build an
  33. impenetrable wall to protect the contained code from accidental
  34. corruption due to the silly little errors that we are all prone to
  35. make.  We also tend to isolate errors to small sections of code to
  36. make them easier to find and fix.  We will have a lot more to say
  37. about the benefits of encapsulation as we progress through the
  38. tutorial.
  39.  
  40.  
  41. NO INFORMATION HIDING
  42. _________________________________________________________________
  43.  
  44. The program named OPEN.CPP is a really stupid      ==============
  45. program because it does next to nothing, but it       OPEN.CPP
  46. will be the beginning point for our discussion     ==============
  47. of encapsulation, otherwise known as information
  48. hiding.  Information hiding is an important part
  49. of object oriented programming and you should have a good grasp of
  50. what it is by the time we finish this chapter.
  51.  
  52. A very simple structure is defined in lines 4 through 6 which
  53. contains a single int type variable within the structure.  This is
  54. sort of a silly thing to do but it will illustrate the problem we
  55. wish to overcome in this chapter.  Three variables are declared in
  56. line 10, each of which contains a single int type variable and each
  57.  
  58.                                                          Page 5-1
  59.  
  60.                                         Chapter 5 - Encapsulation
  61.  
  62. of the three variables are available anywhere within the main
  63. function.  Each variable can be assigned, incremented, read,
  64. modified, or have any number of operations performed on it.  A few
  65. of the operations are illustrated in lines 13 through 21 and should
  66. be self explanatory to anyone with a little experience with the C
  67. programming language.
  68.  
  69. An isolated local variable named piggy is declared and used in the
  70. same section of code to illustrate that there is nothing magic
  71. about this code.
  72.  
  73. Study this simple program carefully because it is the basis for
  74. beginning our study of encapsulation.  Be sure to compile and
  75. execute this program, then we will go on to the next example
  76. program.
  77.  
  78.  
  79. INFORMATION HIDING
  80. _________________________________________________________________
  81.  
  82. Examine the program named CLAS.CPP for our first   ==============
  83. example of a program with a little information        CLAS.CPP
  84. hiding contained in it.  This program is           ==============
  85. identical to the last one except for the way it
  86. does a few of its operations.  We will take the
  87. differences one at a time and explain what is happening here.  Keep
  88. in mind that this is a trivial program and the safeguards built
  89. into it are not needed for such a simple program but are used here
  90. to illustrate how to use these techniques in a larger much more
  91. complicated program.
  92.  
  93. The first difference is that we have a class instead of a structure
  94. beginning in line 4 of this program.  The only difference between
  95. a class and a structure is that a class begins with a private
  96. section whereas a structure has no private section automatically
  97. defined.  The keyword class is used to declare a class as
  98. illustrated here.
  99.  
  100. The class named one_datum is composed of the single variable named
  101. data_store and two functions, one named set() and the other named
  102. get_value().  A more complete definition of a class is a group of
  103. variables and one or more functions that can operate on that data.
  104. Stay with us, we will tie this all together in a meaningful and
  105. useful way very soon.
  106.  
  107.  
  108. WHAT IS A PRIVATE SECTION?
  109. _________________________________________________________________
  110.  
  111. A private section of a class is a section of data which cannot be
  112. accessed outside of the class, it is hidden from any outside
  113. access.  Thus, the variable named data_store which is a part of the
  114. object (an object will be defined completely later) named dog1
  115. declared in line 23 is not available for use anywhere in the main
  116.  
  117.                                                          Page 5-2
  118.  
  119.                                         Chapter 5 - Encapsulation
  120.  
  121. program.  It is as if we have built a "brick wall" around the
  122. variables to protect them from accidental corruption by outside
  123. programming influences.  It seems a little dumb to declare a
  124. variable in the main program that we cannot use, but that is
  125. exactly what we did.
  126.  
  127. Figure 5-1 is a graphical representation of the class with its
  128. "brick wall" built around the data to protect it.  You will notice
  129. the small peep holes we have opened up to allow the user to gain
  130. access to the functions.  The peep holes were opened by declaring
  131. the functions in the public section of the class.
  132.  
  133.  
  134. WHAT IS A PUBLIC SECTION?
  135. _________________________________________________________________
  136.  
  137. A new keyword, public, is introduced in line 6 which states that
  138. anything following this keyword can be accessed from outside of
  139. this class.  Because the two functions are defined following the
  140. keyword public, they are both public and available for use in the
  141. calling function or any other function that is within the scope of
  142. the calling function.  This opens two small peepholes in the solid
  143. wall of protection.  You should keep in mind that the private
  144. variable is not available to the calling program.  Thus, we can
  145. only use the variable by calling one of the two functions defined
  146. as a part of the class.  These are called member functions because
  147. they are members of the class.
  148.  
  149. Since we have declared two functions, we need to define them by
  150. saying what each function will actually do.  This is done in lines
  151. 11 through 19 where they are each defined in the normal way, except
  152. that the class name is prepended onto the function name and
  153. separated from it by a double colon.  These two function
  154. definitions are called the implementation of the functions.  The
  155. class name is required because we can use the same function name
  156. in other classes and the compiler must know with which class to
  157. associate each function implementation.
  158.  
  159. One of the key points to be made here is that the private data
  160. contained within the class is available within the implementation
  161. of the member functions of the class for modification or reading
  162. in the normal manner.  You can do anything with the private data
  163. within the function implementations which are a part of that class,
  164. but the private data of other classes is hidden and not available
  165. within the member functions of this class.  This is the reason we
  166. must prepend the class name to the function names of this class
  167. when defining them.
  168.  
  169. It would be well to mention at this point that it is legal to
  170. include variables and functions in the private part and additional
  171. variables and functions in the public part.  In most practical
  172. situations, variables are included in only the private part and
  173. functions are included in only the public part of a class
  174. definition.  Occasionally, variables or functions are used in the
  175.  
  176.                                                          Page 5-3
  177.  
  178.                                         Chapter 5 - Encapsulation
  179.  
  180. other part.  This sometimes leads to a very practical solution to
  181. a particular problem, but in general, the entities are used only
  182. in the places mentioned.
  183.  
  184. In C++ we have three scopes of variables, local, file and class.
  185. Local variables are localized to a single function and file
  186. variables are available anywhere in a file following their
  187. definition.  A variable with class scope is available anywhere
  188. within the scope of a class and nowhere else.
  189.  
  190. You must be very confused by this point since we have given a lot
  191. of rules but few reasons for doing all of this.  Stay with us and
  192. you will soon see that there are very practical reasons for doing
  193. all of this.
  194.  
  195.  
  196. MORE NEW TERMINOLOGY
  197. _________________________________________________________________
  198.  
  199. As with most new technologies, developers seem to delight in making
  200. up new names for all aspects of their new pet.  Object oriented
  201. programming is no different, so we must learn new names for some
  202. of our old familiar friends if we are going to learn how to
  203. effectively use it.  To help you learn this new programming
  204. terminology, we will list a few of them here and begin using them
  205. in the text to get you used to seeing and using them.
  206.  
  207.      A class is a grouping of data and methods (functions).
  208.      A class is very much like a type as used in ANSI-C, it
  209.      is only a pattern to be used to create a variable which
  210.      can be manipulated in a program.
  211.  
  212.      An object is an instance of a class, which is similar to
  213.      a variable defined as an instance of a type.  An object
  214.      is what you actually use in a program since it has values
  215.      and can be changed.
  216.  
  217.      A method is a function contained within the class.  You
  218.      will find the functions used within a class referred to
  219.      as methods.
  220.  
  221.      A message is the same thing as a function call.  In
  222.      object oriented programming, we send messages instead of
  223.      calling functions.  For the time being, you can think of
  224.      them as identical.  Later in this tutorial we will see
  225.      that they are in fact slightly different.
  226.  
  227. With all the new terminology, we will continue our study of the
  228. program named CLAS.CPP and show you how to use the class.  We can
  229. now say that we have a class composed of one variable and two
  230. methods.  The methods operate on the variable contained in the
  231. class when they receive messages to do so.  In this tutorial we
  232. will use the terms object and variable interchangeably because both
  233. names are very descriptive of what the object really is.
  234.  
  235.                                                          Page 5-4
  236.  
  237.                                         Chapter 5 - Encapsulation
  238.  
  239.  
  240. This is a small point but it could be easily overlooked.  Lines 7
  241. and 8 of this program are actually the prototypes for the two
  242. methods, and is our first example of the use of a prototype within
  243. a class.  This is the reason we spent so much time on prototypes
  244. in the last chapter.  You will notice line 7 which says that the
  245. method named set requires one parameter of type int and returns
  246. nothing, hence the return type is void.  The method named
  247. get_value() however, according to line 8, has no input parameters
  248. but returns an int type value to the caller.
  249.  
  250.  
  251. SENDING A MESSAGE
  252. _________________________________________________________________
  253.  
  254. Following all of the definitions in lines 1 through 19, we finally
  255. come to the program where we actually use the class.  In line 23
  256. we declare three objects of the class one_datum and name the
  257. objects dog1, dog2, and dog3.  Each object contains a single data
  258. point which we can set through use of one method or read its value
  259. through use of the other method, but we cannot directly set or read
  260. the value of the data point because it is hidden within the "block
  261. wall" around the class.  In line 26, we send a message to the
  262. object named dog1 instructing it to set its internal value to 12,
  263. and even though this looks like a function call, it is properly
  264. called sending a message to a method.  Remember that the object
  265. named dog1 has a method associated with it called set() that sets
  266. its internal value to the actual parameter included within the
  267. message.  You will notice that the form is very much like the means
  268. of accessing the elements of a structure.  You mention the name of
  269. the object with a dot connecting it to the name of the method.  In
  270. a similar manner, we send a message to each of the other two
  271. objects dog2 and dog3 to set their values to those indicated.
  272.  
  273. Lines 31 and 32 have been commented out because the operations are
  274. illegal since the variable named data_store is private and not
  275. available to the code outside of the object itself.  It should be
  276. obvious, but it will be pointed out that the data contained within
  277. the object named dog1 is not available within the methods of dog2
  278. or dog3 because they are different objects.  These rules are all
  279. devised to help you develop better code more quickly and you will
  280. soon see how they help.
  281.  
  282. The other method defined for each object is used in lines 34
  283. through 36 to illustrate how it can be used.  In each case, another
  284. message is sent to each object and the returned result is output
  285. to the monitor via the stream library.
  286.  
  287.  
  288. USING A NORMAL VARIABLE
  289. _________________________________________________________________
  290.  
  291. There is another variable named piggy declared and used throughout
  292. this example program that illustrates that a normal variable can
  293.  
  294.                                                          Page 5-5
  295.  
  296.                                         Chapter 5 - Encapsulation
  297.  
  298. be intermixed with the objects and used in the normal manner.  The
  299. use of this variable should pose no problem to you, so after you
  300. understand the program, be sure to compile and execute it.  It
  301. would be a good exercise for you to remove the comments from lines
  302. 31 and 32 to see what kind of error message your compiler issues.
  303.  
  304. This program illustrates information hiding but it will not be
  305. clear to you that it really does anything worthwhile until we study
  306. the next two programs.  Be sure to compile and execute this program
  307. before continuing on to the next example program.
  308.  
  309.  
  310.  
  311. A PROGRAM WITH PROBLEMS
  312. _________________________________________________________________
  313.  
  314. Examine the program named OPENPOLE.CPP for an    ================
  315. example of a program with a few serious problems   OPENPOLE.CPP
  316. that will be overcome in the next example        ================
  317. program by using the principles of
  318. encapsulation.
  319.  
  320. We have two structures declared, one being a rectangle and the
  321. other being a pole.  The data fields should be self explanatory
  322. with the exception of the depth of the flagpole which is the depth
  323. it is buried in the ground, the overall length of the pole is
  324. therefore the sum of the length and the depth.
  325.  
  326. Based on your experience with ANSI-C, you should have no problem
  327. understanding exactly what this program is doing, but you may be
  328. a bit confused at the meaning of the result found in line 38 where
  329. we multiply the height of the square with the width of the box.
  330. This is perfectly legal to do in ANSI-C or C++, but the result has
  331. no earthly meaning because the data are for two different entities.
  332. Likewise, the result calculated in line 40 is even sillier because
  333. the product of the height of the square and the depth of the
  334. flagpole has absolutely no meaning in any real world physical
  335. system we can think up.
  336.  
  337. Wouldn't it be neat if we had a way to prevent such stupid things
  338. from happening in a large production program.  If we had a good
  339. program that defined all of the things we can do with a square and
  340. another program that defined everything we could do with a pole,
  341. and if the data could be kept mutually exclusive, we could prevent
  342. these silly things from happening.
  343.  
  344. It should come as no real surprise to you that the next program
  345. will do just those things for us and do it in a very elegant way.
  346. Before proceeding on to the next example program, you should
  347. compile and execute this one even though it displays some silly
  348. results.
  349.  
  350.  
  351.  
  352.  
  353.                                                          Page 5-6
  354.  
  355.                                         Chapter 5 - Encapsulation
  356.  
  357. OBJECTS PROTECT DATA
  358. _________________________________________________________________
  359.  
  360. Examine the program named CLASPOLE.CPP as an     ================
  361. example of data protection in a very simple        CLASPOLE.CPP
  362. program.                                         ================
  363.  
  364. In this program the rectangle is changed to a
  365. class with the same two variables which are now private, and two
  366. methods to handle the private data.  One method is used to
  367. initialize the values of the objects created and the other method
  368. to return the area of the object.  The two methods are defined in
  369. lines 12 through 21 in the manner described earlier in this
  370. chapter.  The pole is left as a structure to illustrate that the
  371. two can be used together and that C++ is truly an extension of
  372. ANSI-C.
  373.  
  374. In line 33 we declare two objects, once again named box and square,
  375. but this time we cannot assign values directly to their individual
  376. components because they are private elements of the class.  Lines
  377. 36 through 38 are commented out for that reason and the messages
  378. are sent to the objects in lines 40 and 41 to tell them to
  379. initialize themselves to the values input as parameters.  The
  380. flag_pole is initialized in the same manner as in the previous
  381. program.  Using the class in this way prevents us from making the
  382. silly calculations we did in the last program.  The compiler is now
  383. being used to prevent the erroneous calculations.  The end result
  384. is that the stupid calculations we did in the last program are not
  385. possible in this program so lines 50 through 53 have been commented
  386. out.  Once again, it is difficult to see the utility of this in
  387. such a simple program.  In a large program, using the compiler to
  388. enforce the rules can pay off in a big way.
  389.  
  390. Figure 5-2 is a graphical illustration of the two objects available
  391. for use within the calling program.  Even though the square and the
  392. box are both objects of class rectangle, their private data is
  393. hidden from each other such that neither can purposefully or
  394. accidentally change the others data.
  395.  
  396. This is the abstract data type mentioned earlier in this chapter,
  397. a model with an allowable set of variables for data storage and a
  398. set of allowable operations that can be performed on that stored
  399. data.  The only operations that can be performed on the data are
  400. those defined by the methods which prevents many kinds of erroneous
  401. or silly operations.  Encapsulation and data hiding bind the data
  402. and procedures, or methods, tightly together and limit the scope
  403. and visibility of each.  Once again, we have the divide and conquer
  404. technique in which an object is separated from the rest of the code
  405. and carefully developed in complete isolation from it.  Only then
  406. is it integrated into the rest of the code with a few very simple
  407. interfaces.
  408.  
  409.  
  410.  
  411.  
  412.                                                          Page 5-7
  413.  
  414.                                         Chapter 5 - Encapsulation
  415.  
  416. HAVE YOU EVER USED THIS TECHNIQUE BEFORE?
  417. _________________________________________________________________
  418.  
  419. A good example of the use of this technique is in the file commands
  420. you have been using with ANSI-C.  The data in the file is only
  421. available through the predefined functions provided by your
  422. compiler writer.  You have no direct access to the actual data
  423. because it is impossible for you to address the actual data stored
  424. on the disk.  The data is therefore private data, as far as you are
  425. concerned, but the available functions are very much like methods
  426. in C++.  There are two aspects of this technique that really count
  427. when you are developing software.  First, you can get all of the
  428. data you really need from the file system because the interface is
  429. complete, but secondly, you cannot get any data that you do not
  430. need.  You are prevented from getting into the file handling system
  431. and accidentally corrupting some data stored within it.  You are
  432. also prevented from using the wrong data because the functions
  433. available demand a serial access to the data.
  434.  
  435. Another example is in the monitor and keyboard handling routines.
  436. You are prevented from getting into the workings of them and
  437. corrupting them accidentally, or on purpose if you have such a
  438. bent, but once again, you are provided with all of the data
  439. interfaces that you really need.
  440.  
  441. Suppose you are developing a program to analyze some
  442. characteristics of flagpoles.  You would not wish to accidentally
  443. use some data referring to where the flagpole program was stored
  444. on your hard disk as the height of the flagpole, nor would you wish
  445. to use the cursor position as the flagpole thickness or color.  All
  446. code for the flagpole is developed alone, and only when it is
  447. finished, is it available for external use.  When using it, you
  448. have a very limited number of operations which you can do with the
  449. class.  The fact that the data is hidden from you protects you from
  450. accidentally doing such a thing when you are working at midnight
  451. to try to meet a schedule.  Once again, this is referred to as
  452. information hiding and is one of the primary advantages of object
  453. oriented programming over procedural techniques.
  454.  
  455. Based on the discussion given above you can see that object
  456. oriented programming is not really new, since it has been used in
  457. a small measure for as long as computers have been popular.  The
  458. newest development, however, is in allowing the programmer to
  459. partition his programs in such a way that he too can practice
  460. information hiding and reduce the debugging time.
  461.  
  462.  
  463. WHAT DOES THIS COST?
  464. _________________________________________________________________
  465.  
  466. It should be clear that this technique will cost you something in
  467. efficiency because every access to the elements of the object will
  468. require the time and inefficiency of a call to a function, or
  469. perhaps I should be more proper and refer to it as a method.  The
  470.  
  471.                                                          Page 5-8
  472.  
  473.                                         Chapter 5 - Encapsulation
  474.  
  475. time saved in building a large program, however, could easily be
  476. saved in debug time when it comes time to iron out the last few
  477. bugs.  This is because a program made up of objects that closely
  478. match the application are much easier to understand than a program
  479. that does not.
  480.  
  481. This is obviously such a small program that it is silly to try to
  482. see any gain with this technique.  In a real project however, it
  483. could be a great savings if one person developed all of the details
  484. of the rectangle, programmed it, and made it available to you to
  485. simply use.  This is exactly what has been done for you if you
  486. consider the video monitor an object.  There is a complete set of
  487. preprogrammed and debugged routines you can use to make the monitor
  488. do anything you wish it to do, all you have to do is study the
  489. interface to the routines and use them, expecting them to work.
  490. As we mentioned earlier, it is impossible for you to multiply the
  491. size of your monitor screen by the depth of the flag pole because
  492. that information is not available to you to use in a corruptible
  493. way.
  494.  
  495. After you understand some of the advantages of this style of
  496. programming, be sure to compile and execute this program.
  497.  
  498.  
  499. CONSTRUCTORS AND DESTRUCTORS
  500. _________________________________________________________________
  501.  
  502. The file named CONSPOLE.CPP introduces         ==================
  503. constructors and destructors and should be        CONSPOLE.CPP
  504. examined at this time.                         ==================
  505.  
  506. This example program is identical to the last
  507. example except that a constructor has been added as well as a
  508. destructor.  The constructor always has the same name as the class
  509. itself and is declared in line 8, then defined in lines 14 through
  510. 18.  The constructor is called automatically by the C++ system when
  511. the object is declared and can therefore be of great help in
  512. preventing the use of an uninitialized variable.  When the object
  513. named box is declared in line 46, the constructor is called
  514. automatically by the system.  The constructor sets the values of
  515. height and width each to 6 in the object named box.  This is
  516. printed out for reference in lines 49 and 50.  Likewise, when the
  517. square is declared in line 46, the values of the height and the
  518. width of the square are each initialized to 6 when the constructor
  519. is called automatically.
  520.  
  521. A constructor is defined as having the same name as the class
  522. itself.  In this case both are named rectangle.  The constructor
  523. cannot have a return type associated with it since it is not
  524. permitted to have a user defined return type.  It actually has a
  525. predefined return type, a pointer to the object itself, but we will
  526. not be concerned about this until much later in this tutorial.
  527. Even though both objects are assigned values by the constructor,
  528. they are initialized in lines 58 and 59 to new values and
  529.  
  530.                                                          Page 5-9
  531.  
  532.                                         Chapter 5 - Encapsulation
  533.  
  534. processing continues.  Since we have a constructor that does the
  535. initialization, we should probably rename the method named
  536. initialize() something else but it illustrates the concept involved
  537. here.
  538.  
  539. The destructor is very similar to the constructor except that it
  540. is called automatically when each of the objects goes out of scope.
  541. You will recall that automatic variables have a limited lifetime
  542. since they cease to exist when the enclosing block in which they
  543. were declared is exited.  When an object is about to be
  544. automatically deallocated, its destructor, if one exists, is called
  545. automatically.  A destructor is characterized as having the same
  546. name as the class but with a tilde prepended to the class name.
  547. A destructor has no return type.
  548.  
  549. A destructor is declared in line 11 and defined in lines 31 through
  550. 35.  In this case the destructor only assigns zeros to the
  551. variables prior to their being deallocated, so nothing is really
  552. accomplished.  The destructor is only included for illustration of
  553. how it is used.  If some blocks of memory were dynamically
  554. allocated within an object, a destructor should be used to
  555. deallocate them prior to losing the pointers to them.  This would
  556. return their memory to the free store for further use later in the
  557. program.
  558.  
  559. It is interesting to note that if a constructor is used for an
  560. object that is declared prior to the main program, otherwise known
  561. as globally, the constructor will actually be executed prior to the
  562. execution of the main program.  In like manner, if a destructor is
  563. defined for such a variable, it will execute following the
  564. completion of execution of the main program.  This will not
  565. adversely affect your programs, but it is interesting to make note
  566. of.
  567.  
  568.  
  569.  
  570. OBJECT PACKAGING
  571. _________________________________________________________________
  572.  
  573. Examine the file named BOXES1.CPP for an example   ==============
  574. of how not to package an object for universal        BOXES1.CPP
  575. use.  This packaging is actually fine for a very   ==============
  576. small program but is meant to illustrate to you
  577. how to split your program up into smaller more
  578. manageable files when you are developing a large program or when
  579. you are part of a team developing a large system.  The next three
  580. example programs in this chapter will illustrate the proper method
  581. of packaging a class.
  582.  
  583. This program is very similar to the last one with the pole
  584. structure dropped and the class named box.  The class is defined
  585. in lines 4 through 12, the implementation of the class is given in
  586. lines 15 through 34, and the use of the class is given in lines 37
  587. through 50.  With the explanation we gave about the last program,
  588.  
  589.                                                         Page 5-10
  590.  
  591.                                         Chapter 5 - Encapsulation
  592.  
  593. the diligent student should have no problem understanding this
  594. program in detail.
  595.  
  596.  
  597. INLINE IMPLEMENTATION
  598. _________________________________________________________________
  599.  
  600. The method in line 10 contains the implementation for the method
  601. as a part of the declaration because it is very simple, and because
  602. it introduces another new topic which you will use often in C++
  603. programming.  When the implementation is included in the
  604. declaration, it will be assembled inline wherever this function is
  605. called leading to much faster code.  This is because there is no
  606. overhead to accomplish the call to the method.  In some cases this
  607. will lead to code that is both smaller and faster.  This is yet
  608. another illustration of the efficiency built into the C++
  609. programming language.
  610.  
  611. Compile and execute this program in preparation for our study of
  612. the next three examples which are a repeat of this program in a
  613. slightly different form.
  614.  
  615.  
  616. THE CLASS HEADER FILE
  617. _________________________________________________________________
  618.  
  619. If you examine BOX.H carefully, you will see      ===============
  620. that it is only the class definition.  No              BOX.H
  621. details are given of how the various methods are  ===============
  622. implemented except of course for the inline
  623. method named get_area().  This gives the
  624. complete definition of how to use the class with no implementation
  625. details.  You would be advised to keep a hardcopy of this file
  626. available as we study the next two files.  You will notice that it
  627. contains lines 4 through 12 of the previous example program named
  628. BOXES1.CPP.
  629.  
  630. This is called the class header file and cannot be compiled or
  631. executed.
  632.  
  633.  
  634.  
  635. THE CLASS IMPLEMENTATION FILE
  636. _________________________________________________________________
  637.  
  638. Examine the file named BOX.CPP for the            ===============
  639. implementation of the methods declared in the         BOX.CPP
  640. class header file.  Notice that the class header  ===============
  641. file is included into this file in line 2 which
  642. contains all of the prototypes for its methods.
  643. The code from lines 15 through 34 of BOXES1.CPP is contained in
  644. this file which is the implementation of the methods declared in
  645. the class named box.
  646.  
  647.  
  648.                                                         Page 5-11
  649.  
  650.                                         Chapter 5 - Encapsulation
  651.  
  652. This file can be compiled but it cannot be executed because there
  653. is no main entry point which is required for all ANSI-C or C++
  654. programs.  When it is compiled, the object code will be stored in
  655. the current directory and available for use by other programs.  It
  656. should be noted here that the result of compilation is usually
  657. referred to as an object file because it contains object code.
  658. This use of the word object has nothing to do with the word object
  659. as used in object oriented programming.  It is simply a matter of
  660. overloading the use of the word.  The practice of referring to the
  661. compiled result as an object file began long before the method of
  662. object oriented programming was ever considered.
  663.  
  664. The separation of the definition and the implementation is a major
  665. step forward in software engineering.  The definition file is all
  666. the user needs in order to use this class effectively in a program.
  667. He needs no knowledge of the actual implementation of the methods.
  668. If he had the implementation available, he may study the code and
  669. find a trick he could use to make the overall program slightly more
  670. efficient, but this would lead to nonportable software and possible
  671. bugs later if the implementor changed the implementation without
  672. changing the interface.  The purpose of object oriented programming
  673. is to hide the implementation in such a way that the implementation
  674. can not affect anything outside of its own small and well defined
  675. boundary or interface.
  676.  
  677. You should compile this implementation file now and we will use the
  678. result with the next example program.
  679.  
  680.  
  681.  
  682. USING THE BOX OBJECT
  683. _________________________________________________________________
  684.  
  685. Examine the file named BOXES2.CPP and you will   ================
  686. find that the class we defined previously is        BOXES2.CPP
  687. used within this file.  In fact, these last      ================
  688. three programs taken together are identical to
  689. the program named BOXES1.CPP studied earlier.
  690.  
  691. The BOX.H file is included here, in line 3, since the definition
  692. of the box class is needed to declare three objects and use their
  693. methods.  You should have no trouble seeing that this is a repeat
  694. of the previous program and will execute in exactly the same way.
  695. There is a big difference in BOXES1.CPP and BOXES2.CPP as we will
  696. see shortly.
  697.  
  698. A very important distinction must be made at this point.  We are
  699. not merely calling functions and changing the terminology a little
  700. to say we are sending messages.  There is an inherent difference
  701. in the two operations.  Since the data for each object is tightly
  702. bound up in the object, there is no way to get to the data except
  703. through the methods and we send a message to the object telling it
  704. to perform some operation based on its internally stored data.
  705. However, whenever we call a function, we take along the data for
  706.  
  707.                                                         Page 5-12
  708.  
  709.                                         Chapter 5 - Encapsulation
  710.  
  711. it to work with as parameters since it doesn't contain its own
  712. data.
  713.  
  714. Be sure to compile and execute this program, but when you come to
  715. the link step, you will be required to link this program along with
  716. the result of the compilation when you compiled the class named
  717. box.  The file is probably named BOX.OBJ that must be linked with
  718. this file.  You may need to consult the documentation for your C++
  719. compiler to learn how to do this.  Even if it seems to be a lot of
  720. trouble to learn how to link several files together, it will be
  721. worth your time to do so now because we will be linking several
  722. more multifile C++ programs in the remainder of this tutorial.
  723.  
  724. If you are using Turbo C++, this is your first opportunity to use
  725. a project file.  If you are using Zortech C++ or one of the other
  726. implementations, you can use the "make" facility included with your
  727. compiler.  Regardless of which C++ compiler you are using, it would
  728. pay you to stop and learn how to use the multifile technique
  729. provided with your compiler because you will need to use it several
  730. times before the end of this tutorial.  The nature of C++ tends to
  731. drive the programmer to use many files for a given programming
  732. project and you should develop the habit early.
  733.  
  734.  
  735. INFORMATION HIDING
  736. _________________________________________________________________
  737.  
  738. The last three example programs illustrate a method of information
  739. hiding that can have a significant impact on the quality of
  740. software developed for a large project.  Since the only information
  741. the user of the class really needs is the class header, that is all
  742. he needs to be given.  The details of implementation can be kept
  743. hidden from him to prevent him from studying the details and
  744. possibly using a quirk of programming to write some rather obtuse
  745. code.  Since he doesn't know exactly what the implementor did, he
  746. must follow only the definition given in the header file.  This can
  747. have a significant impact on a large project.  As mentioned
  748. earlier, accidental corruption of data is prevented also.
  749.  
  750. Another reason for hiding the implementation is economic.  The
  751. company that supplied you with your C++ compiler gave you many
  752. library functions but did not supply the source code to the library
  753. functions, only the interface to each function.  You know how to
  754. use the file access functions but you do not have the details of
  755. implementation, nor do you need them.  Likewise a class library
  756. industry can develop which supplies users with libraries of high
  757. quality, completely developed and tested classes, for a licensing
  758. fee of course.  Since the user only needs the interface defined,
  759. he can be supplied with the interface and the object (compiled)
  760. code for the class and can use it in any way he desires.  The
  761. suppliers source code is protected from accidental or intentional
  762. compromise and he can maintain complete control over it.
  763.  
  764.  
  765.  
  766.                                                         Page 5-13
  767.  
  768.                                         Chapter 5 - Encapsulation
  769.  
  770. It is very important that you understand the principles covered in
  771. this chapter before proceeding on to the next chapter.  If you feel
  772. you are a little weak in any of the areas covered here, you should
  773. go over them again before proceeding on.  A point that should be
  774. made here that may be obvious to you, is that it requires some
  775. amount of forethought to effectively use classes.
  776.  
  777.  
  778. ABSTRACT DATA TYPES
  779. _________________________________________________________________
  780.  
  781. We mentioned the abstract data type at the beginning of this
  782. chapter and again briefly midway through, and it is time to
  783. describe it a little more completely.  An abstract data type is a
  784. group of data, each of which can store a range of values, and a set
  785. of methods or functions that can operate on that data.  Since the
  786. data are protected from any outside influence, it is protected and
  787. said to be encapsulated.  Also, since the data is somehow related,
  788. it is a very coherent group of data that may be highly interactive
  789. with each other, but with little interaction of its class outside
  790. the scope.
  791.  
  792. The methods, on the other hand, are coupled to the outside world
  793. through the interface, but there are a limited number of contacts
  794. with the outside world and therefore a weak coupling with the
  795. outside.  The object is therefore said to be loosely coupled to the
  796. outside world.  Because of the tight coherency and the loose
  797. coupling, ease of maintenance of the software is greatly enhanced.
  798. The ease of maintenance may be the greatest benefit of object
  799. oriented programming.
  800.  
  801. It may bother you that even though the programmer may not use the
  802. private variables directly outside of the class, they are in plain
  803. sight and he can see what they are and can probably make a good
  804. guess at exactly how the class is implemented.  The variables could
  805. have been hidden completely out of sight in another file, but
  806. because the designers of C++ wished to make the execution of the
  807. completed application as efficient as possible, the variables were
  808. left in the class definition where they can be seen but not used.
  809.  
  810.  
  811. FRIEND FUNCTIONS
  812. _________________________________________________________________
  813.  
  814. A function outside of a class can be defined to be a friend
  815. function by the class which gives the friend free access to the
  816. private members of the class.  This in effect, opens a small hole
  817. in the protective shield of the class, so it should be used very
  818. carefully and sparingly.  There are cases where it helps to make
  819. a program much more understandable and allows controlled access to
  820. the data.  Friend functions will be illustrated in some of the
  821. example programs later in this tutorial.  It is mentioned here for
  822. completeness of this section.  A single isolated function can be
  823. declared as a friend, as well as members of other classes, and even
  824.  
  825.                                                         Page 5-14
  826.  
  827.                                         Chapter 5 - Encapsulation
  828.  
  829. entire classes can be given friend status if needed in a program.
  830. Neither a constructor nor a destructor can be a friend function.
  831.  
  832.  
  833. THE struct IN C++
  834. _________________________________________________________________
  835.  
  836. The struct is still useable in C++ and operates just like it does
  837. in ANSI-C with one addition.  You can include methods in a
  838. structure that operate on data in the same manner as in a class,
  839. but all methods and data are automatically defaulted to be public
  840. in a structure.  Of course you can make any of the data or methods
  841. private by defining a private section within the structure.  The
  842. structure should be used only for constructs that are truly
  843. structures.  If you are building even the simplest objects, you are
  844. advised to use classes to define them.
  845.  
  846.  
  847.  
  848. A VERY PRACTICAL CLASS
  849. _________________________________________________________________
  850.  
  851. The examples of encapsulation used in this chapter have all been
  852. extremely simple in order to illustrate the mechanics of
  853. encapsulation.  Since it would be expedient to study a larger
  854. example the date class is given below for your instruction.  The
  855. date class is a complete nontrivial class which can be used in any
  856. program to get the current date and print it as an ASCII string in
  857. any of four predefined formats.  It can also be used to store any
  858. desired date and format it for display.
  859.  
  860. Examine the file named DATE.H which is the         ==============
  861. header file for the date class.  This file is so       DATE.H
  862. well commented that we don't have much else to     ==============
  863. say about it.  If you understand the principles
  864. covered in this chapter you should have no
  865. problem understanding this class.  The first thing that is new to
  866. you is the reserved word protected which is used in line 12.  We
  867. will define this word in a couple of chapters.  Until then, pretend
  868. that it means the same thing as private and you will be close
  869. enough for this present example.  The code in lines 8 and 9 along
  870. with line 55 will be explained shortly.  For the present time,
  871. simply pretend those lines of code are not there.  Also the keyword
  872. static as used in lines 16 and 17 will be explained later.
  873.  
  874. You should spend the time necessary to completely understand this
  875. class header, with the exception of the new things added, before
  876. going on to the implementation for this class.
  877.  
  878. The file named DATE.CPP is the implementation      ==============
  879. for the date class and once again, there is           DATE.CPP
  880. nothing unusual or difficult about this code.      ==============
  881. It uses very simple logic to store and format
  882. the date in a usable manner.  You should study
  883.  
  884.                                                         Page 5-15
  885.  
  886.                                         Chapter 5 - Encapsulation
  887.  
  888. this code until you understand it completely before going on to the
  889. next example which will use the date class in a main program.
  890.  
  891. The very simple program named USEDATE.CPP is a    ===============
  892. main program that uses the date class to list       USEDATE.CPP
  893. the current date and another date on the          ===============
  894. monitor.  Once again, you should have no problem
  895. understanding this program so nothing more will
  896. be said about it.
  897.  
  898. You should spend the time necessary to understand these three files
  899. because they are the starting point for a practical track in the
  900. next few chapters.  This class will be used in conjunction with
  901. others to illustrate single and multiple inheritance.  Even though
  902. you do not understand all of the details of these files, spend
  903. enough time that you are comfortable with the structure and the
  904. major points of them.
  905.  
  906. We will continue our discussion of encapsulation in the next
  907. chapter.
  908.  
  909.  
  910. PROGRAMMING EXERCISES
  911. _________________________________________________________________
  912.  
  913. 1.   Add a method to CLAS.CPP which will supply the square of the
  914.      stored value.  Include some code in the main program to read
  915.      and display the squared values.
  916.  
  917. 2.   Continuing with CLAS.CPP, add a constructor to initialize the
  918.      stored value to 10 and add a few lines of code to the main
  919.      program to display the values immediately following the object
  920.      definition.
  921.  
  922. 3.   Add an output statement to the rectangle constructor of the
  923.      program named CONSPOLE.CPP and another to the destructor to
  924.      prove to yourself that they really are called by the system
  925.      when we said they are.
  926.  
  927. 4.   Write a more comprehensive program to use the date class
  928.      presented at the end of this chapter.
  929.  
  930. 5.   Write a name class which is somewhat similar to the date class
  931.      which can store any name in three parts and return the full
  932.      name in any of several different formats such as the
  933.      following;
  934.  
  935.            John Paul Doe
  936.            J. P. Doe
  937.            Doe, John Paul
  938.              and any other formats you desire.
  939.  
  940.      If this is carefully planned, it could be useful to you
  941.      someday.
  942.  
  943.                                                         Page 5-16
  944.